package com.xw.util;


import cn.hutool.core.util.RandomUtil;
import com.xw.common.Const;
import com.xw.model.User;
import com.xw.service.sysconfig.UserService;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wangxiaoxiao
 */
public class AppUtil {

    public static void main(String[] args) {
        String orderCode = AppUtil.getOrderCode();
        System.out.println(orderCode);
    }

    /**
     * @需求描述:字符串转时间
     * @创建人:whh
     * @创建时间: 2019/11/15
     * @修改需求:
     * @修改人:
     * @修改时间:
     * @需求思路:
     */
    public static Date stringToDate(String dateStr, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Date date = new Date();

        try {
            date = df.parse(dateStr);
        } catch (ParseException var5) {
            var5.printStackTrace();
        }

        return date;
    }

    /**
     * 去掉开头结尾指定字符
     * @param str
     * @param charStr
     * @return
     */
    public static String removeStartAndEndCharacters(String str,String charStr){
        String newStr="";
        int begin = str.indexOf(charStr);
        if (begin==0) {
            newStr=str.substring(str.indexOf(charStr) + 1);
        }else{
            newStr = str;
        }

        //判断传入的符号是否是最后一个字符
        if (newStr.length() == newStr.lastIndexOf(charStr)+1){
            newStr = newStr.substring(0,newStr.lastIndexOf(charStr));
        }
        return newStr;
    }

    /**
     * 验证app
     * @param request
     * @return
     */
    public static boolean checkApp(HttpServletRequest request){
        String appId = request.getHeader("appId");

        if (Const.CHECK_APPID.equals(appId)){
            return true;
        }
        return false;
    }

    /**
     * 验证web
     * @param request
     * @return
     */
    public static boolean checkWeb(HttpServletRequest request){
        String webId = request.getHeader("webId");

        if (Const.CHECK_WEBID.equals(webId)){
            return true;
        }
        return false;
    }


    /**
     * 验证 token
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request){
        UserService userService = (UserService) SpringBeanFactoryUtils.getBean("userServiceImpl");
        String token = request.getHeader("token");
        String userId = request.getHeader("userId");

        if ("sea".equals(token)){
            return true;
        }

        User user = userService.queryByUUID(userId);
        if (user.getUserToken().equals(token)){
            return true;
        }
        return false;
    }

    public static String md5Salt(String pwd){
        //加密后的字符串
        return  DigestUtils.md5Hex(pwd + Const.MD5_SALT);

    }

    /**
     * 多个参数判断是否为空，空值返回true
     * @param map
     * @return
     */
    public static String checkIsNull(Map<String, Object> map){
        for(Map.Entry<String, Object> entry : map.entrySet()){
            if(entry.getValue() == null || "".equals(entry.getValue()))
                return entry.getKey();
        }
        return Const.SUCCESS_CODE_STR;
    }

    /**
     *
     * @param type 1.操作年份 2.操作月份 3.操作日期 4.操作小时 5.操作分钟 6.操作秒
     * @param num -1向前推  1向后推
     * @return
     */
    public static String calDate(int type,int num){
        Calendar calendar = Calendar.getInstance();
        if (type==1){
            calendar.add(Calendar.YEAR, num);
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
            return format;
        }else if(type==2){
            calendar.add(Calendar.MONTH, num);
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
            return format;
        }else if(type==3){
            calendar.add(Calendar.DAY_OF_MONTH, num);
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
            return format;
        }else if(type==4){
            calendar.add(Calendar.HOUR, num);
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
            return format;
        }else if(type==5){
            calendar.add(Calendar.MINUTE, num);
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
            return format;
        }else if(type==6){
            calendar.add(Calendar.SECOND, num);
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
            return format;
        }
        return "";
    }
    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(Long stap){
        String time;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long lt = stap;
        Date date = new Date(lt);
        time = simpleDateFormat.format(date);
        return time;
    }



    /**
     * 获取时间字符串格式
     */
    public static String dateStr(int type,Date date){
        String pattern="";
        if (type==0){
            pattern="yyyy-MM";
        } else if (type==1){
            pattern="yyyy-MM-dd";
        }else if (type==2){
            pattern="yyyy-MM-dd HH:mm";
        }else if (type==3){
            pattern="yyyy-MM-dd HH:mm:ss";
        }else{
            pattern="yyyy-MM-dd HH:mm:ss";
        }

        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String format = sdf.format(date);
        return format;
    }

    /**
     * 根据传入长度获取随机字符串
     * @param length
     * @return
     */
    public static String getStringRandom(int length) {
        String val = "";
        Random random = new Random();

        for(int i = 0; i < length; ++i) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            if ("char".equalsIgnoreCase(charOrNum)) {
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val = val + (char)(random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val = val + String.valueOf(random.nextInt(10));
            }
        }

        return val;
    }
    /**
     * 将对象转成map ，对象里空值转化成null
     * @param obj
     * @return
     * @throws Exception
     */
    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if(obj == null) {
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Method getter = property.getReadMethod();
            Object value = getter!=null ? getter.invoke(obj) : null;
            map.put(key, value);
        }
        return map;
    }

    /**
     * 获取uuid
     * @return
     */
    public static String uuid(){
        return UUID.randomUUID().toString().replace("-","");
    }

    /**
     * 订单号
     * @return
     */
    public static String getOrderCode() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String randomNumbers = RandomUtil.randomNumbers(4);
        String str = sdf.format(new Date());
        String orderNo = str + randomNumbers;
        return orderNo;
    }

    //根据出生日期计算属相和星座
    private final static int[] dayArr = new int[] { 20, 19, 21, 20, 21, 22, 23,
            23, 23, 24, 23, 22 };
    private final static String[] constellationArr = new String[] { "摩羯座",
            "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座",
            "天蝎座", "射手座", "摩羯座" };

    /**
     * Java通过生日计算星座
     *
     * @param month
     * @param day
     * @return
     */
    public static String getConstellation(int month, int day) {
        return day < dayArr[month - 1] ? constellationArr[month - 1]
                : constellationArr[month];
    }

    /**
     * 通过生日计算属相
     *
     * @param year
     * @return
     */
    public static String getYearOfBirth(int year) {
        if (year < 1900) {
            return "未知";
        }
        int start = 1900;
        String[] years = new String[] { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊",
                "猴", "鸡", "狗", "猪" };
        return years[(year - start) % years.length];
    }


}
